# encoding: utf-8

import cv2
import numpy as np
import argparse

# sudo apt-get install python3-gdal
# sudo apt-get install python-gdal
import gdal



def readTif(fileName):
    dataset = gdal.Open(fileName)
    if dataset == None:
        print(fileName, "open fail")
        return
    im_width = dataset.RasterXSize #栅格矩阵的列数
    im_height = dataset.RasterYSize #栅格矩阵的行数
    im_bands = dataset.RasterCount #波段数
    print 'w:', im_width, 'h:', im_height
    im_data = dataset.ReadAsArray(0,0,im_width,im_height)#获取数据


    im_blueBand =  im_data[0:im_height,0:im_width]#获取蓝波段
    # im_greenBand = im_data[1,0:im_height,0:im_width]#获取绿波段
    # im_redBand =   im_data[2,0:im_height,0:im_width]#获取红波段
    # im_nirBand = im_data[3,0:im_height,0:im_width]#获取近红外波段
    return im_width,im_height,im_bands,im_blueBand
def linearstretching(img,min,max):

    np.clip(img,min,max)
    # img=np.where(img > min, img, min)
    # img=np.where(img < max, img, max)
    img = (img - min) / (max - min) * 255
    return img
def minmaximg(width,heigh,img):
    img_fla = img.flatten() #展成一维数组
    #img_fla = np.sort(img_fla) #排序
    len=img.max()
    print('max=%d' % len)
    num=np.zeros(len+1,dtype=np.int32)
    print('size=%d'%np.size(img_fla))
    for i in np.arange(np.size(img_fla)):
        num[img_fla[i]]=num[img_fla[i]]+1
        #print('img_fla= %d,%d'%(i,img_fla[i]))
        #print('num %d,%d' % (i, num[img_fla[i]]))
    p=0
    min=0
    max=0
    print(np.sum(num))
    for j in np.arange(len+1):
        p = num[j] / (width*heigh) + p
        #print('/n',num[j])
        if p>=0.2:
            min=j
            break
    p=0

    for j in np.arange(len+1):
        p = num[j] / (width * heigh) + p
        # print('/n,%', num[j])
        # print('/n,%', p)
        # print('/n,%', j)
        if p >= 0.90:
            max = j
            break
    return min,max

def show_tiff(tiff_file):
    # img = cv2.imread(tiff_file, flags=cv2.IMREAD_ANYDEPTH)
    print 'read road:', tiff_file
    im_width, im_height, im_bands, tiff = readTif(tiff_file)
    # tiff = readTiff(tiff_file)
    tiff = np.abs(tiff)
    # real=tiff.real()

    # bmin, bmax = minmaximg(im_width, im_height, tiff)
    # tiff = tiff.real
    # tiff = np.array(tiff, dtype='uint8')
    mean = np.mean(tiff)

    tiff = linearstretching(tiff, 0, 3*mean)
    return tiff

    # im_blueBand = np.transpose(im_blueBand, (1, 2, 0))
    # im_blueBand=im_blueBand[:,:,0]
    # cv2.imwrite('data/sar_tif/write_rec2.png', tiff)
    # img = cv2.merge([im_blueBand, im_blueBand, im_blueBand])
    # cv2.imwrite('./001.png', tiff)
# def readTiff( tif_path ) :
#     tif = TIFF.open(tif_path, mode = 'r')
#     img = tif.read_image()
#     return img


# 文件名后缀
tiff_extension = ".tiff"


if __name__ == "__main__":
    # ls date | sed "s:^::" >> list.txt
    list_road = './list.txt'
    data_road = './date/'
    save_road = './img/'
    with open(list_road, 'r') as f:  # 只读
        # print(f.read())
        ii = 0
        for file_name in f:
            file_name = file_name.strip('\n')
            file_road = data_road + file_name
            print ii
            ii += 1

            file_name = file_name.strip().split(".")
            # print file_name[0]
            save_name = save_road + file_name[0] + '.png'

            tiff = show_tiff(file_road)
            print 'save road:', save_name
            cv2.imwrite(save_name, tiff)

